#include <stdio.h>
#include <time.h>
#include <tgmath.h>
#include <pthread.h>
#include <stdint.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>

#define NIT_SHORT_NAMES
#include <nit/socket.h>

#include "tp.h"

#define SEC_TO_NANO 1e9 /* billion */

int
blu_tp(Nit_joint *in, Nit_joint *out, Blu_tpad *ad, Blu_tpre *re)
{
	const char *c = ad->bytes;
	struct timespec timer = {
		.tv_sec = trunc(ad->spc),
		.tv_nsec = SEC_TO_NANO * (ad->spc - trunc(ad->spc))
	};

	for (; ad->size - (c - ad->bytes) > ad->chunk; c += ad->chunk) {
		if (!joint_send(out, c, ad->chunk))
			return 0;

		if (nanosleep(&timer, NULL) < 0)
			return 0;
	}

	if (!joint_send(out, c, ad->size - (c - ad->bytes)))
		return 0;

	return 1;
}
